//
//  LOMedia.m
//  LegalObserver
//
//  Created by Roxanne Brittain on 11/1/11.
//  Copyright (c) 2011 Digifit. All rights reserved.
//

#import "LOMedia.h"
#import "LOAppDelegate.h"
#import <MediaPlayer/MediaPlayer.h>

@implementation LOMedia
@synthesize type, duration, image, thumbnailImage, imageFilename, thumbnailImageFilename, videoURL, dateCreated, title, location, notes;

-(id)initWithImage:(UIImage *)i
{
    self = [super init];
    if (self) {
        image = i;
        imageFilename = [NSString stringWithFormat:@"image%f.jpg", [NSDate timeIntervalSinceReferenceDate]];
        thumbnailImageFilename = [NSString stringWithFormat:@"thumb%@", imageFilename];
        [self saveImageFile];
        type = MEDIA_TYPE_PHOTO;
        dateCreated = [NSDate date];
    }
    return self;
}

-(void)saveImageFile
{
    NSString *doc = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];        
    NSString *filePath = [NSString stringWithFormat:@"%@/%@",doc, imageFilename];
    NSData *data = [NSData dataWithData: UIImageJPEGRepresentation(image, 1)];
    if (![data writeToFile:filePath atomically:YES]) NSLog(@"image save failed");
}

-(void)saveThumbnailImageFile
{
    NSString *doc = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];        
    NSString *filePath = [NSString stringWithFormat:@"%@/%@",doc, thumbnailImageFilename];
    NSData *data = [NSData dataWithData: UIImageJPEGRepresentation(thumbnailImage, 1)];
    if (![data writeToFile:filePath atomically:YES]) NSLog(@"image save failed");
}

-(id)initWithVideoURL:(NSURL *)v
{
    self = [super init];
    if (self) {
        videoURL = v;
        type = MEDIA_TYPE_VIDEO;
        dateCreated = [NSDate date];
        imageFilename = [NSString stringWithFormat:@"image%f.jpg", [NSDate timeIntervalSinceReferenceDate]];
        thumbnailImageFilename = [NSString stringWithFormat:@"thumb%@", imageFilename];
        
        p = [[MPMoviePlayerController alloc] initWithContentURL:videoURL];
        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(movieDurationAvailable:) name:MPMovieDurationAvailableNotification object:nil];
    }
    return self;
}

-(void)dealloc
{
    [[NSNotificationCenter defaultCenter] removeObserver:self name:MPMovieDurationAvailableNotification object:nil];
}

-(void)movieDurationAvailable:(NSNotification*)notification
{
    if (duration==0) duration = p.duration;
}

-(UIImage *)thumbnailImage
{
    NSLog(@"%@", thumbnailImageFilename);
    if (!thumbnailImage) {
        NSString *doc = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];
        NSString *filePath = [NSString stringWithFormat:@"%@/%@",doc, thumbnailImageFilename];
        thumbnailImage = [[UIImage alloc] initWithContentsOfFile:filePath];
    }
    
    if (!thumbnailImage || (type==MEDIA_TYPE_VIDEO && duration==0)) {
        
        NSLog(@"generating thumbnail");
        UIImage *i;
        if (type == MEDIA_TYPE_PHOTO) {
            i = self.image;
            
            //aspect fill
            float w = i.size.width;
            float h = i.size.height;
            float newH, newW;
            if (w>h) {
                newH = 75;
                newW = round((newH/h) * w);
            } else {
                newW = 75;
                newH = round((newW/w) * h);
            }
            
            UIGraphicsBeginImageContextWithOptions(CGSizeMake(75, 75), YES, [UIScreen mainScreen].scale);
            [i drawInRect:CGRectMake(-(newW-75)/2, -(newH-75)/2, newW, newH)];
            
        } else {
            MPMoviePlayerController *player = [[MPMoviePlayerController alloc] initWithContentURL:videoURL];
            i = [player thumbnailImageAtTime:0 timeOption:MPMovieTimeOptionNearestKeyFrame];
            
            UIGraphicsBeginImageContextWithOptions(CGSizeMake(75, 75), YES, [UIScreen mainScreen].scale);
            CGContextRef context = UIGraphicsGetCurrentContext(); 
            [i drawAtPoint:CGPointMake(0, 0)];
            CGContextSetRGBFillColor(context, 0, 0, 0, 0.5);
            CGContextFillRect(context, CGRectMake(0, 55, 75, 20));
            
            if (duration==0) duration = [player duration];
            int s = duration;
            NSString *text = (s>0) ? [NSString stringWithFormat:@"%01d:%02d", s/60, s%60] : @"-:--"; 
            CGContextSetRGBFillColor(context, 1, 1, 1, 1);
            [text drawAtPoint:CGPointMake(4, 55) withFont:[UIFont boldSystemFontOfSize:15]];
            
        }
        
        thumbnailImage = UIGraphicsGetImageFromCurrentImageContext();
        [self saveThumbnailImageFile];
        
        UIGraphicsEndImageContext();
    }
    
    return thumbnailImage;
}

-(UIImage *)image
{
    if (!image) {
        NSString *doc = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];
        NSString *filePath = [NSString stringWithFormat:@"%@/%@",doc, imageFilename];
        image = [[UIImage alloc] initWithContentsOfFile:filePath];
    }
    return image;
}

-(NSString*)stringDescription
{
    return [NSString stringWithFormat:@"Title: %@\nDate: %@\nLocation: %@\nNotes: %@\n", title, [LOAppDelegate stringFromDate:dateCreated], location, notes];
}

- (void)encodeWithCoder:(NSCoder *)coder {
    [coder encodeInt:duration forKey:@"duration"];
    [coder encodeInt:type forKey:@"type"];
    [coder encodeObject:imageFilename forKey:@"imageFilename"];
    [coder encodeObject:thumbnailImageFilename forKey:@"thumbnailImageFilename"];
    [coder encodeObject:videoURL forKey:@"videoURL"];
    [coder encodeObject:dateCreated forKey:@"dateCreated"];
    [coder encodeObject:title forKey:@"title"];
    [coder encodeObject:location forKey:@"location"];
    [coder encodeObject:notes forKey:@"notes"];
}

- (id)initWithCoder:(NSCoder *)coder {
    self = [super init];
    duration = [coder decodeIntForKey:@"duration"];
    type = [coder decodeIntForKey:@"type"];
    imageFilename = [coder decodeObjectForKey:@"imageFilename"];
    thumbnailImageFilename = [coder decodeObjectForKey:@"thumbnailImageFilename"];
    videoURL = [coder decodeObjectForKey:@"videoURL"];
    dateCreated = [coder decodeObjectForKey:@"dateCreated"];
    title = [coder decodeObjectForKey:@"title"];
    location = [coder decodeObjectForKey:@"location"];
    notes = [coder decodeObjectForKey:@"notes"];
    return self;
}

@end
